import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import 'dy_exception.dart';

/// 全局错误处理 及 loading提示
class DyErrorManager extends Interceptor {
  final _requestStack = [];

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (_requestStack.isEmpty) {
      SmartDialog.showLoading(msg: '加载中...');
    }
    _requestStack.add(true);
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _requestStack.removeAt(0);
    if (_requestStack.isEmpty) {
      SmartDialog.dismiss();
    }
    if ((response.statusCode == 200 || response.statusCode == 201) && response.requestOptions.responseType == ResponseType.json) {
      var data = response.data is String ? jsonDecode(response.data) : response.data;
      if (data is List) {

      } else if (data['error'] != null) {
        dynamic error;
        if (data['error']['code'] == 100) {
          var sessionExpiredException = AppException(-1, '会话已过期，请重新等登录', AppException.sessionExpiredCallback);
          error = sessionExpiredException;
        } else {
          var appException = AppException(-1, data['error']['data']['message'] ?? '未知错误');
          error = appException;
        }
        var err = DioException(requestOptions: response.requestOptions, error: error);
        return handler.reject(err);
      } else if (data['errorcode'] == 'session_expired') {
        var sessionExpiredException = AppException(-1, '会话已过期，请重新等登录', AppException.sessionExpiredCallback);
        var err = DioException(requestOptions: response.requestOptions, error: sessionExpiredException);
        return handler.reject(err);
      } else if (data['errorcode'] == 'error') {
        var appException = AppException(-1, data['msg'] ?? '未知错误');
        var err = DioException(requestOptions: response.requestOptions, error: appException);
        return handler.reject(err);
      }
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    SmartDialog.dismiss();
    AppException appException = AppException.create(err);
    super.onError(err.copyWith(error: appException), handler);
  }
}
